﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.IoUtils;
using CatUtils.Utils.Enhance.TypeConvert;
using CatUtils.Utils.Helper;
using CatUtils.Utils.SpecialUtils.View;
using CatUtilsDll.Utils.Currency.TextUtils;
using Newtonsoft.Json;
using System;
using WordPressSharp;
using WordPressSharp.Models;

namespace CatUtils.Utils.SpecialUtils.Wordpress
{/// <summary>
/// wordpress文件帮助
/// </summary>
    public class WordpressHelper
    {
        /// <summary>
        /// 用户信息保存路径
        /// </summary>
        public static string UserInfoPath { get; set; } = StaticValue.BinPath + "UserInfoPath\\";

        /// <summary>
        ///  创建并且返回标签
        /// </summary>
        /// <param name="client"></param>
        /// <param name="tag"></param>
        /// <returns></returns>
        public static Term CreateTagHelper(WordPressClient client, string tag)
        {
            Term TermTemp = new Term() { Taxonomy = "post_tag", Name = tag }; // new up a term object to attach to post. The Name is the one we want to look for or create

            try
            {
                Term[] SearchTerms = client.GetTerms("post_tag", new TermFilter() { Search = TermTemp.Name }); // get term names from API searching for the one we want

                if (SearchTerms == null)
                {
                    string term_id = CreateTerm(client, tag, TermTemp);
                    if (term_id != "")
                        TermTemp.Id = term_id;
                    else
                        return null;
                }
                else
                {//搜索到相关结果，进行完全匹配
                    foreach (var term in SearchTerms)
                    {
                        if (string.Equals(term.Name, TermTemp.Name, StringComparison.CurrentCultureIgnoreCase))
                        {
                            Console.WriteLine("标签已有：{0}", term.Name);
                            TermTemp.Id = term.Id; // the Term exists already, grab it's id and attach it to our object
                        }
                    }
                    //没有获得完全匹配的结果。创建
                    if (TermTemp.Id == null)
                    {
                        // oh nos the search results didnt have the exact one we are looking for. lets create!
                        try
                        {
                            string term_id = CreateTerm(client, tag, TermTemp);
                            if (term_id != "")
                                TermTemp.Id = term_id;
                            else
                                return null;
                        }
                        catch (Exception ex)
                        {
                            PrintLog.Log(ex);
                            return null;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
            return TermTemp;
        }

        private static string CreateTerm(WordPressClient client, string tag, Term TermTemp)
        {
            string Sulg = Transcoding.UrlDeCode(tag);
            string term_id = "";
            if (Sulg.Length > 20)
            {
                Console.WriteLine("过长");
                Sulg = "dm" + DateTime.Now.ToFileTime().ToString();
            }
            TermTemp.Slug = Sulg;

            try
            {
                term_id = client.NewTerm(TermTemp);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
                return null;
            }

            return term_id;
        }

        /// <summary>
        /// wp发布用用户初始化
        /// </summary>
        public struct UserInfo
        {/// <summary>
         /// 用户名
         /// </summary>
            public string UserName { get; set; }

            /// <summary>
            /// 用户密码
            /// </summary>
            public string Password { get; set; }

            /// <summary>
            /// 发布的HOST URL  例如:https://baiud.com/
            /// </summary>
            public string Indexurl { get; set; }
        }

        /// <summary>
        /// 在本地添加用户信息
        /// </summary>
        /// <param name="UserName"></param>
        /// <param name="UserPass"></param>
        /// <param name="WebSite"></param>
        /// <param name="FileName"></param>
        public void AddUserInfo(string UserName, string UserPass, string WebSite, string FileName)
        {
            try
            {
                WordpressHelper.UserInfoLocalJson userInfo = new WordpressHelper.UserInfoLocalJson() { name = UserName, pass = UserPass, url = WebSite };
                string WriteJson = JsonConvert.SerializeObject(userInfo);
                string SavePath = FileName + ".dat";
                if (WriteJson == "" || SavePath == "")
                {
                    MessageHelper.Alert("保存用户文件出错！");
                    return;
                }
                WriteJson = new Base64Convert().EnBase64(WriteJson);
                string FilePath = UserInfoPath + SavePath;
                FileHelper.WriteText(FilePath, WriteJson);
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
                MessageHelper.Alert("保存用户文件出错！");
            }
        }

        /// <summary>
        /// 解密已经加密的用户信息辅助方法
        /// </summary>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        public UserInfo ReadUserInfo(string FilePath)
        {
            if (!FileHelper.FileExits(FilePath, true))
                return new UserInfo();
            string Json = FileHelper.ReadAllText(FilePath);
            Json = new Base64Convert().DeBase64(Json);
            UserInfo Temp = new UserInfo();
            try
            {
                UserInfoLocalJson UserJson = JsonConvert.DeserializeObject<UserInfoLocalJson>(Json);
                Temp.UserName = UserJson.name;
                Temp.Password = UserJson.pass;
                Temp.Indexurl = UserJson.url;
            }
            catch (Exception ex)
            {
                PrintLog.Log(ex);
            }
            return Temp;
        }

        /// <summary>
        /// 初始化wpclient
        /// </summary>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        public WordPressClient InitClient(string FilePath)
        {
            return InitClient(ReadUserInfo(FilePath));
        }

        /// <summary>
        /// 初始化用户信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <returns></returns>

        public WordPressClient InitClient(UserInfo userInfo)
        {
            var client = new WordPressClient(new WordPressSiteConfig
            {
                BaseUrl = userInfo.Indexurl,
                Username = userInfo.UserName,
                Password = userInfo.Password,
                BlogId = 1
            });
            return client;
        }

        /// <summary>
        /// 读取文本信息初始化
        /// </summary>
        public class UserInfoLocalJson
        {
            /// <summary>
            ///
            /// </summary>
            public string name { get; set; }

            /// <summary>
            ///
            /// </summary>
            public string pass { get; set; }

            /// <summary>
            ///
            /// </summary>
            public string url { get; set; }
        }

        //    public static SendPublish(Post Post,Client)
    }
}